import uuid
from datetime import datetime, timedelta

from sqlalchemy import Column, String, DateTime, Integer, Date, or_
from sqlalchemy.orm import declarative_base

from x_tw.db import Session

Base = declarative_base()


class VehicleTask(Base):
    """
    发车任务
    """
    __tablename__ = 'wops_vehicle_task'

    id = Column(String(32), primary_key=True, nullable=False, comment='编号')
    plan_begin = Column(DateTime, nullable=False, comment='计划开始时间')
    plan_end = Column(DateTime, nullable=False, comment='计划结束时间')
    deliver_factory = Column(String(32), nullable=False, comment='交付工厂')
    deliver_factory_code = Column(String(32), nullable=False, comment='交付工厂编码')
    ems_case_deliver_port_num = Column(String(32), comment='可同时占用交货口:发ems箱形态时可同时占用口')
    ems_pallet_deliver_port_num = Column(String(32), comment='可同时占用交货口:发栈板形态时出口情况')
    work_date = Column(Date, comment='工作日')
    pallet_begin = Column(DateTime, nullable=False, comment='栈板出货开始时间')
    pallet_end = Column(DateTime, nullable=False, comment='栈板出货结束时间')
    box_begin = Column(DateTime, nullable=False, comment='箱式出货开始时间')
    box_end = Column(DateTime, nullable=False, comment='箱式出货结束时间')

    def __init__(self, plan_begin: datetime, plan_end: datetime, deliver_factory: str, deliver_factory_code: str,
                 ems_case_deliver_port_num: str, ems_pallet_deliver_port_num: str, work_date, pallet_begin: datetime,
                 pallet_end: datetime, box_begin: datetime, box_end: datetime):
        self.id = self.key()
        self.plan_begin = plan_begin
        self.plan_end = plan_end
        self.deliver_factory = deliver_factory
        self.deliver_factory_code = deliver_factory_code
        self.ems_case_deliver_port_num = ems_case_deliver_port_num
        self.ems_pallet_deliver_port_num = ems_pallet_deliver_port_num
        self.work_date = work_date
        self.pallet_begin = pallet_begin
        self.pallet_end = pallet_end
        self.box_begin = box_begin
        self.box_end = box_end

    def to_dict(self):
        # 返回对象属性的字典副本
        return {key: value for key, value in self.__dict__.items()}

    @staticmethod
    def key() -> str:
        return str(uuid.uuid4()).replace('-', '')


class VehicleOrderDetail(Base):
    """
    发车任务 - 订单明细 关联
    """
    __tablename__ = 'wops_vehicle_orderdetail'

    id = Column(String(32), primary_key=True, nullable=False)
    wops_vehicle_taskid = Column(String(32), nullable=False, comment='发车任务ID')
    orderdetailid = Column(String(32), nullable=False, comment='订单明细ID')

    def __init__(self, task_id, order_detail_id):
        self.id = self.key()
        self.wops_vehicle_taskid = task_id
        self.orderdetailid = order_detail_id

    @staticmethod
    def key() -> str:
        return str(uuid.uuid4()).replace('-', '')


class WaveOrderSku(Base):
    """
    大波次交付sku量
    """
    __tablename__ = 'wops_wave_order_sku'

    id = Column(String(32), primary_key=True, nullable=False, comment='编号')
    is_urgent = Column(Integer, nullable=False, comment='是否紧急')
    orderdetil = Column(String(32), nullable=False, comment='关联的订单编号')
    sku = Column(String(32), nullable=False, comment='sku')
    num = Column(Integer, nullable=False, comment='PCS数')
    deliver_factory = Column(String(32), comment='交付对象')
    deliver_factory_code = Column(String(32), comment='交付对象编码')
    wops_delivery_time_windowid = Column(String(32), nullable=False)
    wops_vehicle_taskid = Column(String(32), nullable=False)
    pallet_num = Column(Integer, nullable=False, comment="栈板数")
    pallet_pcs_num = Column(Integer, nullable=False, comment="栈板PCS数")
    box_num = Column(Integer, nullable=False, comment="箱数")
    box_pcs_num = Column(Integer, nullable=False, comment="箱式PCS数")

    def __init__(self, **kwargs):
        self.id = self.key()
        for k in kwargs:
            if hasattr(self, k):
                setattr(self, k, kwargs[k])

    def to_dict(self):
        # 返回对象属性的字典副本
        return {key: value for key, value in self.__dict__.items()}

    @staticmethod
    def key() -> str:
        return str(uuid.uuid4()).replace('-', '')


class VehicleOrderService(object):
    """
    输出服务封装
    """

    @staticmethod
    def save_task(task_list: list[VehicleTask]):
        """
        保存发车任务
        :param task_list:
        :return:
        """
        with Session() as sess:
            sess.add_all(task_list)
            sess.commit()

    @staticmethod
    def save_task_order(to_list: list[VehicleOrderDetail], vehicle_taskid_arr):
        """
        保存 任务 订单 关系
        :param to_list:
        :param vehicle_taskid_arr:
        :return:
        """
        with (Session() as sess):
            date_now = datetime.now().strftime('%Y-%m-%d')
            # 给当前日期加一天
            date_next_day = datetime.now() + timedelta(days=1)
            date_next_day = date_next_day.strftime('%Y-%m-%d')
            # 获取所有当天所有未完成的车任务数据
            vehicle_task_list = sess.query(VehicleTask).filter(~VehicleTask.id.in_(vehicle_taskid_arr)).filter(or_(
                    VehicleTask.work_date == date_now,
                    VehicleTask.work_date == date_next_day
                )
            )
            task_id_list = [vehicle_task.id for vehicle_task in vehicle_task_list]
            # 删除数据
            sess.query(VehicleOrderDetail).filter(VehicleOrderDetail.wops_vehicle_taskid.in_(task_id_list)).delete()
            sess.query(WaveOrderSku).filter(WaveOrderSku.wops_vehicle_taskid.in_(task_id_list)).delete()
            vehicle_task_list.delete()
            sess.add_all(to_list)
            sess.commit()

    @staticmethod
    def save_wave_order(wos_list: list[WaveOrderSku]):
        with Session() as sess:
            sess.add_all(wos_list)
            sess.commit()


if __name__ == '__main__':
    pass
    # with (Session() as sess):
    #     vehicle_taskid_arr = ['00b65cc5d8b24b51bd72de5613fff771', '14e837c1acc649da99f9787e31ab8063']
    #     date_now = datetime.now().strftime('%Y-%m-%d')
    #     # 获取所有当天所有未完成的车任务数据
    #     vehicle_task_list = sess.query(VehicleTask).filter(~VehicleTask.id.in_(vehicle_taskid_arr)).filter(
    #         VehicleTask.work_date == date_now)
    #     task_id_list = [vehicle_task.id for vehicle_task in vehicle_task_list]
    #     # 删除数据
    #     sess.query(VehicleOrderDetail).filter(VehicleOrderDetail.wops_vehicle_taskid.in_(task_id_list)).delete()
    #     sess.query(WaveOrderSku).filter(WaveOrderSku.wops_vehicle_taskid.in_(task_id_list)).delete()
    #     vehicle_task_list.delete()
    #     sess.commit()
